package com.flyemu.share.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.lang.Assert;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.style.StyleUtil;
import com.alibaba.fastjson.JSONObject;
import com.flyemu.share.annotation.SaAccountVal;
import com.flyemu.share.annotation.SaMerchantId;
import com.flyemu.share.annotation.SaOrganizationId;
import com.flyemu.share.dto.AccountDto;
import com.flyemu.share.entity.Order;
import com.flyemu.share.form.SalesOrderForm;
import com.flyemu.share.service.SalesOrderService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * @功能描述: 销售订单
 * @创建时间: 2024年06月13日
 * @公司官网: www.fenxi365.com
 * @公司信息: 纷析云（杭州）科技有限公司
 * @公司介绍: 专注于财务相关软件开发, 企业会计自动化解决方案
 */
@RestController
@RequestMapping("/salesOrder")
@RequiredArgsConstructor
@SaCheckLogin
public class SalesOrderController {
    private final SalesOrderService orderService;

    /**
     * 销售订单列表
     *
     * @param merchantId
     * @param page
     * @param query
     * @return
     */
    @GetMapping
    public JsonResult list(Page page, SalesOrderService.Query query, @SaMerchantId Long merchantId, @SaOrganizationId Long organizationId) {
        query.setMerchantId(merchantId);
        query.setOrganizationId(organizationId);
        return JsonResult.successful(orderService.query(page, query));
    }


    /**
     * 出库单可关联的订单list
     *
     * @param merchantId
     * @param customersId
     * @return
     */
    @GetMapping("selectList/{customersId}")
    public JsonResult selectList( @PathVariable Long customersId,@SaMerchantId Long merchantId,@SaOrganizationId Long organizationId) {
        return JsonResult.successful(orderService.toSelect(customersId,merchantId,organizationId));
    }


    /**
     * 出库单关联的order详情
     *
     * @param merchantId
     * @param orderId
     * @return
     */
    @GetMapping("selectLoad/{orderId}")
    public JsonResult selectLoad( @PathVariable Long orderId,@SaMerchantId Long merchantId,@SaOrganizationId Long organizationId) {
        return JsonResult.successful(orderService.selectLoad(orderId,merchantId,organizationId));
    }

    /**
     * 根据条件导出销售订单数据
     * @param merchantId
     * @param organizationId
     * @param query
     * @return
     */
    @GetMapping("/downCondition")
    public ResponseEntity<byte[]> downCondition(SalesOrderService.Query query, @SaMerchantId Long merchantId, @SaOrganizationId Long organizationId) {
        query.setMerchantId(merchantId);
        query.setOrganizationId(organizationId);
        return toExcel("销售订单数据.xlsx", orderService.downloadList(merchantId,organizationId ,query ), null);
    }


    /**
     * 条件内销售订单总金额
     *
     * @param merchantId
     * @param query
     * @return
     */
    @GetMapping("/total")
    public JsonResult queryTotal(SalesOrderService.Query query, @SaMerchantId Long merchantId, @SaOrganizationId Long organizationId) {
        query.setMerchantId(merchantId);
        query.setOrganizationId(organizationId);
        return JsonResult.successful(orderService.queryTotal(query));
    }

    /**
     * 客户销售订单
     * @param customersId
     * @param merchantId
     * @param organizationId
     * @return
     */
    @GetMapping("/listBy/{customersId}")
    public JsonResult listBy( @PathVariable Long customersId,@SaMerchantId Long merchantId,@SaOrganizationId Long organizationId) {
        return JsonResult.successful(orderService.listBy( customersId,merchantId,organizationId));
    }

    /**
     * 保存销售订单
     *
     * @param salesOrderForm
     * @param accountDto
     * @return
     */
    @PostMapping
    public JsonResult save(@RequestBody SalesOrderForm salesOrderForm, @SaAccountVal AccountDto accountDto) {
        //TODO 所有单据判断小于等于结账时间有问题，如果新建账套，则无法保存订单
//        Assert.isTrue(salesOrderForm.getSalesOrder().getBillDate().isAfter(accountDto.getCheckDate()),"小于等于结账时间:"+accountDto.getCheckDate()+"不能修改数据");
        orderService.save(salesOrderForm, accountDto.getAdminId(), accountDto.getMerchantId(), accountDto.getOrganizationId(), accountDto.getMerchant().getCode());
        return JsonResult.successful();
    }


    /**
     * 更新销售订单状态
     *
     * @param order
     * @param accountDto
     * @return
     */
    @PutMapping
    public JsonResult updateState(@RequestBody Order order, @SaAccountVal AccountDto accountDto) {
        orderService.updateState(order,accountDto);
        return JsonResult.successful();
    }


    /**
     * 销售订单详情
     *
     * @param merchantId
     * @param orderId
     * @return
     */
    @GetMapping("load/{orderId}")
    public JsonResult load(@SaMerchantId Long merchantId, @PathVariable Long orderId, @SaOrganizationId Long organizationId) {
        return JsonResult.successful(orderService.load(merchantId, orderId, organizationId));
    }



    /**
     * 删除销售订单
     *
     * @param orderId
     * @param merchantId
     * @return
     */
    @DeleteMapping("/{orderId}")
    public JsonResult delete(@PathVariable Long orderId, @SaMerchantId Long merchantId, @SaOrganizationId Long organizationId) {
        orderService.delete(orderId, merchantId, organizationId);
        return JsonResult.successful();
    }


    private ResponseEntity<byte[]> toExcel(String filename, List<JSONObject> downloadList, List<String> headStrings) {
        ExcelWriter writer = ExcelUtil.getBigWriter("销售订单数据");
        Workbook workbook = writer.getWorkbook();
        Font font = StyleUtil.createFont(workbook, Font.COLOR_RED, (short) 11, null);
        CellStyle cellStyle = StyleUtil.cloneCellStyle(workbook, writer.getStyleSet().getHeadCellStyle());
        cellStyle.setFont(font);
        if (headStrings == null) {
            headStrings = Arrays.asList("销售订单号", "客户名称", "单据日期", "下单时间", "原始金额", "优惠金额", "订单金额", "订单状态",  "制单人","备注");
        }
        writer.writeHeadRow(headStrings);

        writer.setCurrentRow(1).write(downloadList);
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        writer.flush(byteOutputStream);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HttpHeaders.CONTENT_TYPE, ExcelUtil.XLSX_CONTENT_TYPE);
        httpHeaders.setContentDisposition(ContentDisposition.builder("attachment")
                .filename(filename, StandardCharsets.UTF_8).build());
        return new ResponseEntity<>(byteOutputStream.toByteArray(),
                httpHeaders,
                HttpStatus.OK);
    }
}
